<template>
  <div class="app-container">
    <div class="searchBox">
      <el-form :inline="true" :model="search" ref="searchForm">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="search.name" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item style="margin-top: -2px">
          <el-button type="primary" @click="searchQuery">查询</el-button>
          <el-button type="info" @click="search = {};searchQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <qm-table
      :data="query"
      keyProp="roleId"
      :showView="false"
      menuType="text"
      :formOptions="{ labelWidth: '120px' }"
      :rules="rules"
    >
      <qm-table-column field="name" sortable>中文名称</qm-table-column>
      <qm-table-column field="code" sortable>编码</qm-table-column>
      <qm-table-column field="isEnabled" fieldtype="enabledisable" sortable width="100px">是否启用</qm-table-column>
      <template v-slot:moreBtn="{ row }">
        <el-dropdown>
          <el-button style="padding-left: 7px;" size="mini" type="text">更多</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="handleCommand(row)">分配权限</el-dropdown-item>
            <el-dropdown-item @click.native="handleCommand2(row)">分配用户</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
      <template v-slot:form="{ model, viewModel }">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称：" prop="model.name">
              <el-input v-model="model.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统编码：" prop="model.code">
              <el-input v-model="model.code"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否启用：" prop="model.isEnabled">
              <el-radio v-model="model.isEnabled" :label="true">是</el-radio>
              <el-radio v-model="model.isEnabled" :label="false">否</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扩展1：" prop="model.reserved1">
              <el-input v-model="model.reserved1"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="扩展2：" prop="model.reserved2">
              <el-input v-model="model.reserved2"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扩展3：" prop="model.reserved3">
              <el-input v-model="model.reserved3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="viewModel.pageAction === 'view'">
          <el-col :span="12">
            <el-form-item label="创建时间：" prop="model.createdDate">
              <el-date-picker type="datetime" v-model="model.createdDate" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间：" prop="model.updatedDate">
              <el-date-picker type="datetime" v-model="model.updatedDate" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </qm-table>

    <el-dialog :title="row.name+'分配用户'" :visible.sync="dialogUserVisible" @closed="dialogUserClose">
      <el-row>
        <el-col :span="6">
          <el-select
            v-model="searchUsers"
            value-key="value"
            multiple
            filterable
            remote
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
          >
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="`${item.label}（${item.loginId}）`"
              :value="item"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-button type="primary" @click="addNew" icon="el-icon-plus">添加</el-button>
        </el-col>
        <el-col :span="6" :offset="2">
          <el-cascader
            v-model="departmentId"
            clearable
            filterable
            placeholder="请选择部门"
            :options="deptTree"
            :show-all-levels="false"
            :props="{value:'id',label:'text',checkStrictly:true}"
          ></el-cascader>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-button type="warning" @click="batchAddNew" icon="el-icon-plus">批量添加</el-button>
        </el-col>
      </el-row>
      <qm-table
        ref="qmTable"
        v-if="dialogUserVisible"
        :urls="{query:'/admin/sysRole/setUsers/query'}"
        :beforeQuery="beforeQuery"
        :showView="false"
        :showEdit="false"
        :showDelete="false"
      >
        <qm-table-column field="userName" sortable>用户名称</qm-table-column>
        <template v-slot:moreBtn="{ row }">
          <el-button @click="doRemove(row)">移除</el-button>
        </template>
      </qm-table>
    </el-dialog>

    <el-dialog :title="row.name+'分配权限'" :visible.sync="dialogMenuVisible" @closed="dialogMenuClose">
      <el-tree
        :data="treeData"
        ref="tree"
        node-key="id"
        :props="props"
        :default-expanded-keys="idslist"
        :default-checked-keys="idslist"
        show-checkbox
        check-strictly
        @check-change="handleCheckChange"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveMenus">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Controller from "@/libs/framework/controller";
import request from "@/utils/request";
export default class Instance extends Controller {
  onBeforeInit() {
    this.urls = {
      query: [{ url: "/admin/sysRole/query", method: "post" }],
      save: "/admin/sysRole/save",
      delete: "/admin/sysRole/delete",
      entity: "/admin/sysRole/getEntity",
    };
  }

  mixin() {
    return {
      data() {
        return {
          //分配用户dialog的数据
          dialogUserVisible: false,
          searchUsers: [],
          //下拉框数据
          users: [],
          deptTree: [],
          departmentId: null,
          //当前行对象
          row: {},
          //分配权限dialog的数据
          dialogMenuVisible: false,
          treeData: [],
          idslist: [],
          props: {
            children: "children",
            label: "text",
            id: "id",
          },
          rules: {
            model: {
              name: [
                {
                  required: true,
                  message: "请输入角色名称",
                  trigger: "blur",
                },
              ],
              code: [
                {
                  required: true,
                  message: "请输入参数编码",
                  trigger: "blur",
                },
              ],
              isEnabled: [
                {
                  required: true,
                  message: "请选择是否启用",
                },
              ],
            },
          },
        };
      },
      created() {},
      methods: {
        handleCheckChange() {},
        saveMenus() {
          this.idslist = this.$refs.tree.getCheckedKeys();
          request({
            url: "/admin/sysRole/saveMenus2",
            method: "post",
            data: {
              roleId: this.row.roleId,
              menus: this.idslist,
            },
          })
            .then((r) => {
              this.dialogMenuVisible = false;
              if (r && !r.initMessage) {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        beforeQuery(parmas) {
          parmas.query.roleId = this.row.roleId;
        },
        dialogUserClose() {
          this.dialogUserVisible = false;
          this.searchUsers = [];
          this.departmentId = null;
          this.row = {};
        },
        dialogMenuClose() {
          this.dialogUserVisible = false;
          this.row = {};
          this.treeData = [];
          this.idslist = [];
        },
        handleCommand(row) {
          this.row = row;
          this.dialogMenuVisible = true;
          this.setMenus();
        },
        handleCommand2(row) {
          this.row = row;
          this.dialogUserVisible = true;
          this.remoteMethod();
          this.selectDep();
        },
        remoteMethod(query) {
          request({
            url: "/admin/sysRole/setUsers/userSelect2",
            method: "get",
            params: { term: query },
          })
            .then((r) => {
              if (r && !r.initMessage) {
                this.users = r.data.map((m) => {
                  return {
                    value: m.userId,
                    userId: m.userId,
                    label: m.userName,
                    loginId: m.loginId,
                  };
                });
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        selectDep() {
          request({
            url: "/admin/sysDepartment/selectDep",
            method: "get",
          })
            .then((r) => {
              if (r && !r.initMessage) {
                this.deptTree = r;
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        setMenus() {
          request({
            url: "/admin/sysRole/setMenus2",
            method: "get",
            params: {
              roleId: this.row.roleId,
            },
          })
            .then((r) => {
              if (r && !r.initMessage) {
                this.treeData = r.parameters.treeData;
                this.idslist = r.parameters.list;
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        addNew() {
          if (null == this.searchUsers || this.searchUsers.length == 0) {
            this.$message("请先选择授予的人员!");
            return;
          }
          this.searchUsers.forEach((item) => {
            delete item.label;
            delete item.value;
          });
          request({
            url: "/admin/sysRole/addUsers2Role",
            method: "post",
            data: {
              roleId: this.row.roleId,
              users: this.searchUsers,
            },
          })
            .then((r) => {
              if (r && !r.initMessage) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.$refs["qmTable"].refresh();
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        batchAddNew() {
          if (null == this.departmentId || this.departmentId.length == 0) {
            this.$message("请先选择一个部门!");
            return;
          }
          let departmentId = this.departmentId[this.departmentId.length - 1];
          request({
            url: "/admin/sysRole/addUsersByDept2",
            method: "post",
            data: {
              departmentId: departmentId,
              roleId: this.row.roleId,
            },
          })
            .then((r) => {
              if (r && !r.initMessage) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.$refs["qmTable"].refresh();
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        doRemove(row) {
          this.$confirm("确定要移除么？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              request({
                url: "/admin/sysRole/removeUser",
                method: "get",
                params: {
                  userId: row.userId,
                  roleId: row.roleId,
                },
              })
                .then((r) => {
                  if (r && !r.initMessage) {
                    this.$message({
                      message: "删除成功",
                      type: "success",
                    });
                    this.$refs["qmTable"].refresh();
                  } else {
                    reject(r.initMessage || "数据请求失败");
                  }
                })
                .catch((e) => {
                  reject(e);
                });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        },
      },
    };
  }
}
</script>

<style scoped lang="less">
</style>

